<script lang="ts" setup>
interface Props {
  loading?: boolean;
  error?: null | {
    message: string;
    title: string;
  };
  loadingText?: string;
  showRetry?: boolean;
  showBack?: boolean;
}

interface Emits {
  (e: 'retry'): void;
  (e: 'back'): void;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  error: null,
  loadingText: '加载中...',
  showRetry: true,
  showBack: true,
});

const emit = defineEmits<Emits>();

const handleRetry = () => {
  emit('retry');
};

const handleBack = () => {
  emit('back');
};
</script>

<template>
  <div class="loading-wrapper">
    <div v-if="loading" class="loading-container">
      <a-spin :spinning="true" :tip="loadingText">
        <div class="loading-placeholder"></div>
      </a-spin>
    </div>

    <div v-else-if="error" class="error-container">
      <a-result status="error" :title="error.title" :sub-title="error.message">
        <template #extra>
          <a-button type="primary" @click="handleRetry"> 重试 </a-button>
          <a-button @click="handleBack"> 返回 </a-button>
        </template>
      </a-result>
    </div>

    <div v-else class="content-container">
      <slot></slot>
    </div>
  </div>
</template>

<style lang="less" scoped>
.loading-wrapper {
  position: relative;
  min-height: 200px;

  .loading-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 200px;

    .loading-placeholder {
      width: 100%;
      height: 200px;
    }
  }

  .error-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 200px;
  }

  .content-container {
    width: 100%;
  }
}
</style>
